package com.mypack.web;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mypack.util.Assert;

/**
 * dispatch client request to diffierent method
 * the target method arguments must be HttpServletRequest request, HttpServletResponse response
 * and throws Exception
 * <p>for example : 
 * <code>public void execute(HttpServletRequest request, HttpServletResponse response)
 *			throws Exception</code>
 * <p>also child class not allow to override <code>service</code> method
 * but you can do this, if you really want to do so. <br>
 * in this case , action lost the dispatch request capability
 * @date 2011-01-26 23:15
 * @author z3y2
 */
public class DispatchAction extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
	 * Logger object, child can use it too
	 */
	protected final Logger logger = Logger.getLogger(getClass().getName());
	
	/**
	 * all method object client can call according http
	 */
	private Map<String, Method> methods;
	
	/**
	 * the parameter name from client, must be 'method' and not support config now
	 */
	private static final String METHOD = "method";
	
	public DispatchAction() {
		Method[] methodArray = getClass().getMethods();
		methods = new ConcurrentHashMap<String, Method>(methodArray.length);
		for (Method method : methodArray) {
			// parameter types must match the standard method signature
			if (matches(method)) {
				methods.put(method.getName(), method);
			}
		}
		if (logger.isLoggable(Level.INFO)) {
			logger.info("All methods are ---> ");
			for (Map.Entry<String, Method> entry : methods.entrySet()) {
				logger.info(entry.getKey() + " = " + entry.getValue());
			}
		}
	}
	
	private boolean matches(Method method) {
		Class<?>[] exceptionTypes = method.getExceptionTypes();
		if (exceptionTypes == null || exceptionTypes.length != 1) {
			return false;
		}
		if (exceptionTypes[0] != Exception.class) {
			return false;
		}
		Class<?>[] argsTypes = method.getParameterTypes();
		if (argsTypes == null || argsTypes.length != 2) {
			return false;
		}
		if (argsTypes[0] != HttpServletRequest.class) {
			return false;
		}
		if (argsTypes[1] != HttpServletResponse.class) {
			return false;
		}
		return true;
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String methodName = request.getParameter(METHOD);
		Assert.hasText(methodName, "Method name must not be null.");
		Method targetMethod = methods.get(methodName);
		
		if (logger.isLoggable(Level.INFO)) {
			logger.info("client request method is " + methodName);
		}
		
		if (targetMethod == null) {
			throw new ServletException("client requested method not founded, method name --> " + methodName);
		}
		
		try {
			targetMethod.invoke(this, new Object[]{request, response});
		} catch (Exception ex) {
			logger.log(Level.WARNING, "error occurs when execute " + methodName, ex);
			throw new ServletException("error occurs where execute " + methodName, ex);
		}
	}
}
